﻿using System;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Linq.Expressions;
using System.Collections.Generic;
using System.Threading.Tasks;
using YiSha.Util;
using YiSha.Util.Extension;
using YiSha.Util.Model;
using YiSha.Data;
using YiSha.Data.Repository;
using YiSha.Entity.YiDongYuan;
using YiSha.Model.Param.YiDongYuan;
using YiSha.Web.Code;

namespace YiSha.Service.YiDongYuan
{
    /// <summary>
    /// 创 建：admin
    /// 日 期：2021-06-09 12:00
    /// 描 述：检测详细信息服务类
    /// </summary>
    public class DetectionInfoService : RepositoryFactory
    {
        #region 获取数据

        public async Task<List<DetectionInfoEntity>> GetList(DetectionInfoListParam param)
        {
            var expression = ListFilter(param);
            var list = await this.BaseRepository().FindList(expression);
            return list.ToList();
        }

        public async Task<List<DetectionInfoEntity>> GetPageList(DetectionInfoListParam param, Pagination pagination)
        {
            var expression = ListFilter(param);
            var list = await this.BaseRepository().FindList(expression, pagination);
            return list.ToList();
        }

        public async Task<DetectionInfoEntity> GetEntity(long id)
        {
            return await this.BaseRepository().FindEntity<DetectionInfoEntity>(id);
        }

        #endregion 获取数据

        #region 提交数据

        public async Task SaveForm(DetectionInfoEntity entity, OperatorInfo user)
        {
            var db = this.BaseRepository();
            await db.BeginTrans();
            try
            {
                if (entity.Id.IsNullOrZero())
                {
                    entity.BaseCreateTime = DateTime.Now;
                    entity.Id = IdGenerator.IdGeneratorHelper.Instance.GetId();
                    //entity.BaseCreatorId从小程序获取;
                    entity.BillNo = $"JXHFD{DateTime.Now:yyyyMMddhhmmssfff}";
                    var resultEntity = await db.FindEntity<DetectionResultEntity>(entity.ResultDataId.Value);
                    entity.EndTime = resultEntity.testingtime;
                    entity.BeginTime = entity.EndTime.Value.AddSeconds(new Random().Next(-150, -100));
                    var deviceEntity = await db.FindEntity<DetectionDeviceEntity>(t => t.YDJXLH == resultEntity.DeviceID);
                    entity.AccLimit = resultEntity.acclimits;
                    if (deviceEntity != null)
                    {
                        entity.XTBH = deviceEntity.XTBH;
                        entity.YDJBH = deviceEntity.YDJBH;
                        entity.YDJCJ = deviceEntity.YDJCJ;
                        entity.YDJJDRQ = deviceEntity.YDJJDRQ;
                        entity.YDJXH = deviceEntity.YDJXH;
                        entity.ZSYBH = deviceEntity.ZSYBH;
                        entity.ZSYCJ = deviceEntity.ZSYCJ;
                        entity.ZSYJDRQ = deviceEntity.ZSYJDRQ;
                        entity.ZSYXH = deviceEntity.ZSYXH;
                    }

                    var taskEntity = await db.FindEntity<DetectionTaskEntity>(entity.TaskId.Value);
                    var mechanics = await db.FindEntity<DetectionMechanicsEntity>(taskEntity.MechanicsId.Value);
                    switch (mechanics.PFJD)
                    {
                        case "1":
                        case "2":
                            entity.ZXXZLB = "Ⅰ类";
                            break;

                        case "3":
                        case "4":
                        case "5":
                        case "6":
                            entity.ZXXZLB = "Ⅱ类";
                            break;

                        default:
                            entity.ZXXZLB = "Ⅱ类";
                            break;
                    }
                    //判断低排区是否合格
                    //功率>=37，则检测平均值必须<=0.5
                    //功率<37，则检测平均值必须<=0.8
                    if (mechanics.FDJGL.ParseToDecimal() >= 37)
                        entity.ResultDPQ = (resultEntity.accavg <= 0.5) ? 0 : 1;
                    else
                        entity.ResultDPQ = (resultEntity.accavg <= 0.8) ? 0 : 1;
                    await db.Insert(entity);
                    taskEntity.DetectionInfoId = entity.Id;
                    taskEntity.DetectionInfoResult = entity.Result;
                    taskEntity.DetectionStatus = 1;
                    taskEntity.DetectionTime = resultEntity.testingtime;
                    //taskEntity.DetectionUserId = entity.BaseCreatorId;
                    taskEntity.AuditStatus = 0;
                    await db.Update(taskEntity);
                }
                else
                {
                    await db.Update(entity);
                }
                await db.CommitTrans();
            }
            catch (Exception ex)
            {
                await db.RollbackTrans();
                throw;
            }
        }

        public async Task DeleteForm(string ids)
        {
            long[] idArr = TextHelper.SplitToArray<long>(ids, ',');
            await this.BaseRepository().Delete<DetectionInfoEntity>(idArr);
        }

        #endregion 提交数据

        #region 私有方法

        private Expression<Func<DetectionInfoEntity, bool>> ListFilter(DetectionInfoListParam param)
        {
            var expression = LinqExtensions.True<DetectionInfoEntity>();
            if (param != null)
            {
                if (!string.IsNullOrEmpty(param.Ids))
                {
                    long[] idList = TextHelper.SplitToArray<long>(param.Ids, ',');
                    expression = expression.And(t => idList.Contains(t.Id.Value));
                }
                if (!param.TaskId.IsNullOrZero())
                {
                    expression = expression.And(t => t.TaskId == param.TaskId);
                }
            }
            return expression;
        }

        #endregion 私有方法
    }
}
